import requests
import logging
logger = logging.getLogger(__name__)

class ResourceHelper:
    req_timeout = 20
    def __init__(self, base_uri):
        self.base_uri = base_uri

    def get_operator_info(self, operator_id):
        try:
            url = f"{self.base_uri}/operator/{operator_id}"
            response = requests.get(url, timeout=self.req_timeout)
            res = self._handle_response(response)
        except Exception as e:
            raise Exception(f"get_operator_info failed: {e}") from e

        logger.debug("get_operator_info from res helper: %s", res)
        return res

    def get_algo_info(self, algo_id):
        try:
            url = f"{self.base_uri}/algo/{algo_id}"
            response = requests.get(url, timeout=self.req_timeout)
            res = self._handle_response(response)
        except Exception as e:
            raise Exception(f"get algo info failed: {e}") from e

        logger.debug("get algo from res helper: %s", res)
        return res

    def get_file_signature(self, object_name, expire = 60):
        try:
            url = f"{self.base_uri}/file/sign"
            data = {
                "objectName": object_name,
                "expire": expire
            }
            logger.debug("get_file_signature from res helper: %s, uri: %s", data, url)
            response = requests.post(url, json=data, timeout=self.req_timeout)
            res = self._handle_response(response)
        except Exception as e:
            raise Exception(f"get file signature failed: {e}") from e

        logger.debug("get_file_signature from res helper: %s", res)
        return res

    def task_async(self, data):
        try:
            url = f"{self.base_uri}/taskAlgo/save"
            logger.debug("async task to res: %s, uri: %s", data, url)
            response = requests.post(url, json=data, timeout=self.req_timeout)
            res = self._handle_response(response)
        except Exception as e:
            raise Exception(f"async task to res failed: {e}") from e
        logger.debug("async task to res: %s", res)
        return res

    def task_status_async(self, data):
        try:
            url = f"{self.base_uri}/taskAlgo/taskStatusAsync"
            # logger.debug("async task status to res: %s, uri: %s", data, url)
            response = requests.post(url, json=data, timeout=self.req_timeout)
            res = self._handle_response(response)
        except Exception as e:
            raise Exception(f"async task status to res failed: {e}") from e
        logger.debug("async task status to res: %s", res)
        return res

    def _handle_response(self, response):
        if response.status_code != 200:
            try:
                error_details = response.json()
            except ValueError:
                error_details = {'message': 'cannot decode response by Json'}
            raise Exception(f"HTTP Error {response.status_code}: {error_details.get('message')}")

        result = response.json()
        if not result.get('success', False):
            raise Exception(f"remote return success:false : {result.get('message')}")

        return result['data']

